// src/services/redisClient.ts
import { Cluster } from 'ioredis';
import config from '../config';

// 创建并导出 Redis 集群实例
export const redisCluster = new Cluster(
  [
    { host: '10.166.152.206', port: 8531 },
    { host: '10.166.152.206', port: 8533 },
    { host: '10.166.152.206', port: 8534 },
    { host: '10.166.152.206', port: 8532 },
    { host: '10.166.152.206', port: 8535 },
    { host: '10.166.152.206', port: 8536 },
  ],
  {
    redisOptions: {
      password: config.redis.password,
      showFriendlyErrorStack: true,
    },
    scaleReads: 'slave',
    slotsRefreshTimeout: 5000,
    dnsLookup: (address, callback) => callback(null, address),
    maxRedirections: 32,
    enableOfflineQueue: true,
    enableReadyCheck: true,
  }
);

// 添加错误处理
redisCluster.on('error', (err) => {
  console.error('Redis Cluster Error');
});

// 连接成功日志
redisCluster.on('connect', () => {
  console.log('Redis Cluster connected');
});

// 连接就绪日志
redisCluster.on('ready', () => {
  console.log('Redis Cluster ready');
});

// 重连日志
redisCluster.on('reconnecting', () => {
  console.log('Redis Cluster reconnecting...');
});

// 关闭连接日志
redisCluster.on('close', () => {
  console.log('Redis Cluster connection closed');
});

// 导出单例实例
export default redisCluster;